package com.taoym.voucher.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.taoym.voucher.admin.domain.XcxActivityOrder;
import com.taoym.voucher.admin.domain.XcxUserInfo;
import com.taoym.voucher.admin.entity.dto.XcxActivityOrdersDTO;
import com.taoym.voucher.admin.entity.vo.SysGetUserDetailVO;
import com.taoym.voucher.admin.entity.vo.XcxGetActivityOrdersVO;
import com.taoym.voucher.admin.mapper.XcxActivityOrderMapper;
import com.taoym.voucher.admin.mapper.XcxUserInfoMapper;
import com.taoym.voucher.admin.service.SysUserService;
import com.taoym.voucher.admin.service.XcxActivityOrderService;
import com.taoym.voucher.common.enums.ActInfoEnum;
import com.taoym.voucher.common.response.OrderSyncResp;
import com.taoym.voucher.common.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @coder taoym
 * @datetime 2021/6/28 18:07
 * @desc
 */
@Service
public class XcxActivityOrderServiceImpl implements XcxActivityOrderService {

    @Resource
    private XcxActivityOrderMapper xcxActivityOrderMapper;
    @Value("${jutuike.order}")
    private String jutuikeOrder;
    @Autowired
    private SysUserService sysUserService;
    @Resource
    private XcxUserInfoMapper xcxUserInfoMapper;

    @Override
    public XcxGetActivityOrdersVO getOrderList(XcxActivityOrdersDTO data) {
        List<XcxActivityOrder> orderList = xcxActivityOrderMapper.getOrderList((data.getPage() - 1) * data.getSize(),
                data.getSize(), data.getStatus(), data.getUid());
        if (CollectionUtils.isEmpty(orderList)) {
            return null;
        }
        Integer count = xcxActivityOrderMapper.countOrderList(data.getStatus(), data.getUid());

        XcxGetActivityOrdersVO xcxGetActivityOrdersVO = new XcxGetActivityOrdersVO();
        xcxGetActivityOrdersVO.setCount(count);
        xcxGetActivityOrdersVO.setGetActivityOrders(JSON.parseArray(JSON.toJSONString(orderList), XcxGetActivityOrdersVO.GetActivityOrder.class));
        return xcxGetActivityOrdersVO;
    }

    @Override
    public Integer syncHistoryOrder() {

        SysGetUserDetailVO personal = sysUserService.personal();
        Map<String, Object> params = new HashMap<>();
        params.put("apikey", personal.getApiKey());
        params.put("end_time", LocalDateTime.now());
        params.put("page", 1);
        params.put("pageSize", 100);

        // 下单者佣金率 = 可分配佣金率*队员佣金率
        BigDecimal distRate = new BigDecimal(personal.getDistRate());
        BigDecimal teamRate = new BigDecimal(personal.getTeamRate());
        BigDecimal orderUserRate = distRate.multiply(teamRate).setScale(3, BigDecimal.ROUND_DOWN);

        // 邀请人佣金=可分配佣金率*(1-下单者佣金率)
        BigDecimal chiefRate = distRate.multiply(new BigDecimal("1")
                .subtract(teamRate)).setScale(3, BigDecimal.ROUND_DOWN);

        // 存放用户uid和用户邀请人uid的容器
        Map<String, String> chiefUidMaps = new HashMap<>();
        boolean flag = true;
        Integer count = 0;
        do {
            String response = HttpClientUtils.doPost(jutuikeOrder, JSON.toJSONString(params));
            OrderSyncResp orderSyncResp = JSON.parseObject(response, OrderSyncResp.class);

            if (!ObjectUtils.isEmpty(orderSyncResp) &&
                    orderSyncResp.getCode().equals(1) &&
                    !ObjectUtils.isEmpty(orderSyncResp.getData()) &&
                    !ObjectUtils.isEmpty(orderSyncResp.getData().getData())) {
                Integer insertCount = syncOrder(orderSyncResp.getData().getData(), chiefUidMaps, orderUserRate, chiefRate);
                count = count + insertCount;
                // 如果当前页等于最后一页 则不需要再查询了
                if (params.get("page").equals(orderSyncResp.getData().getLast_page())) {
                    flag = false;
                } else {
                    // 否则 查询下一页
                    params.put("page", orderSyncResp.getData().getCurrent_page() + 1);
                }
            }
        } while (flag);
        return count;
    }

    public Integer syncOrder(List<OrderSyncResp.Order> orders, Map<String, String> chiefUidMaps, BigDecimal orderUserRate, BigDecimal chiefRate) {

        List<XcxActivityOrder> xcxActivityOrders = new ArrayList<>(orders.size());
        for (OrderSyncResp.Order order : orders) {

            String chiefUid = chiefUidMaps.get(order.getSid());
            if (ObjectUtils.isEmpty(chiefUid)) {
                XcxUserInfo xcxUserInfo = xcxUserInfoMapper.selectOne(new QueryWrapper<XcxUserInfo>()
                        .select("chief_uid")
                        .eq("uid", order.getSid()));
                chiefUid = ObjectUtils.isEmpty(xcxUserInfo) ? "000000" : xcxUserInfo.getChiefUid();
                chiefUidMaps.put(order.getSid(), chiefUid);
            }

            XcxActivityOrder xcxActivityOrder = new XcxActivityOrder();
            xcxActivityOrder.setOrderSn(order.getOrderSn());
            xcxActivityOrder.setOrderPrice(order.getOrderPrice());
            xcxActivityOrder.setOrderTitle(order.getOrderTitle());
            xcxActivityOrder.setActId(order.getActId());
            xcxActivityOrder.setActName(order.getActName());
            xcxActivityOrder.setCreateTime(order.getCreateTime());
            xcxActivityOrder.setPayTime(order.getPayTime());
            xcxActivityOrder.setAllFee(order.getJtk_share_fee());
            xcxActivityOrder.setAllRate(order.getJtk_share_rate());
            xcxActivityOrder.setOrderUserUid(order.getSid());
            xcxActivityOrder.setChiefUid(chiefUid);
            xcxActivityOrder.setPayPrice(order.getPayPrice());
            xcxActivityOrder.setModifiedTime(order.getModifiedTime());
            xcxActivityOrder.setStatus(order.getStatus());
            xcxActivityOrder.setStatusDesc(order.getStatus_desc());

            // 活动的相关信息
            ActInfoEnum actInfoEnum = ActInfoEnum.getInstance(order.getActId());
            String rate = ObjectUtils.isEmpty(actInfoEnum) ? "0.85" : actInfoEnum.getRate();
            BigDecimal rateBigDecimal = new BigDecimal(rate);
            // 实际佣金
            BigDecimal realFee = new BigDecimal(order.getJtk_share_fee())
                    .multiply(rateBigDecimal).setScale(3, BigDecimal.ROUND_DOWN);
            xcxActivityOrder.setRealFee(realFee.toString());
            // 实际佣金率
            xcxActivityOrder.setRealRate(new BigDecimal(order.getJtk_share_rate())
                    .multiply(rateBigDecimal).setScale(3, BigDecimal.ROUND_DOWN).toString());
            // 下单人佣金率和佣金
            xcxActivityOrder.setOrderUserRate(orderUserRate.toString());
            xcxActivityOrder.setOrderUserFee(realFee.multiply(orderUserRate)
                    .setScale(3, BigDecimal.ROUND_DOWN).toString());
            // 邀请人佣金率和佣金
            xcxActivityOrder.setChiefRate(chiefRate.toString());
            xcxActivityOrder.setChiefFee(realFee.multiply(chiefRate).setScale(3, BigDecimal.ROUND_DOWN).toString());

            xcxActivityOrder.setOrderPrice(order.getOrderPrice());

            xcxActivityOrders.add(xcxActivityOrder);
        }

        if (!CollectionUtils.isEmpty(xcxActivityOrders)) {
            return xcxActivityOrderMapper.insertOrUpdateList(xcxActivityOrders);
        }
        return 0;
    }
}
